<template>
  <div class="admin-container">
    <el-container>
      <el-header class="header">
        <div class="header-left">
          <h2>校园报修系统 - 管理员</h2>
        </div>
        <div class="header-right">
          <span>欢迎，{{ userStore.userInfo?.name }}</span>
          <el-button type="text" @click="handleLogout">
            <el-icon><SwitchButton /></el-icon>
            退出登录
          </el-button>
        </div>
      </el-header>
      
      <el-container>
        <el-aside width="200px" class="sidebar">
          <el-menu
            :default-active="activeMenu"
            class="sidebar-menu"
            @select="handleMenuSelect"
          >
            <el-menu-item index="repair">
              <el-icon><Tools /></el-icon>
              <span>报修管理</span>
            </el-menu-item>
            <el-menu-item index="staff">
              <el-icon><User /></el-icon>
              <span>后勤人员管理</span>
            </el-menu-item>
          </el-menu>
        </el-aside>
        
        <el-main class="main-content">
          <!-- 报修管理 -->
          <div v-if="activeMenu === 'repair'" class="repair-section">
            <div class="section-header">
              <h3>报修管理</h3>
              <el-button type="primary" @click="refreshRepairs">刷新</el-button>
            </div>
            
            <el-table :data="repairs" style="width: 100%" v-loading="loading">
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="title" label="标题" />
              <el-table-column prop="description" label="描述" show-overflow-tooltip />
              <el-table-column prop="location" label="地点" />
              <el-table-column prop="status" label="状态">
                <template #default="{ row }">
                  <el-tag :type="getStatusType(row.status)">
                    {{ getStatusText(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="创建时间" width="180" />
              <el-table-column label="操作" width="200">
                <template #default="{ row }">
                  <el-button size="small" @click="editRepair(row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="deleteRepairItem(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            
            <!-- 分页组件 -->
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="repairCurrentPage"
                v-model:page-size="repairPageSize"
                :page-sizes="[5, 10, 20, 50]"
                :total="repairTotal"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleRepairSizeChange"
                @current-change="handleRepairCurrentChange"
              />
            </div>
          </div>
          
          <!-- 后勤人员管理 -->
          <div v-if="activeMenu === 'staff'" class="staff-section">
            <div class="section-header">
              <h3>后勤人员管理</h3>
              <el-button type="primary" @click="showAddStaffDialog">新增人员</el-button>
            </div>
            
            <el-table :data="staffList" style="width: 100%" v-loading="staffLoading">
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="username" label="用户名" />
              <el-table-column prop="name" label="姓名" />
              <el-table-column prop="position" label="工作岗位" />
              <el-table-column prop="createTime" label="创建时间" width="180" />
              <el-table-column label="操作" width="200">
                <template #default="{ row }">
                  <el-button size="small" @click="editStaff(row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="deleteStaff(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            
            <!-- 分页组件 -->
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="staffCurrentPage"
                v-model:page-size="staffPageSize"
                :page-sizes="[5, 10, 20, 50]"
                :total="staffTotal"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleStaffSizeChange"
                @current-change="handleStaffCurrentChange"
              />
            </div>
          </div>
        </el-main>
      </el-container>
    </el-container>
    
    <!-- 编辑报修对话框 -->
    <el-dialog v-model="repairDialogVisible" title="编辑报修" width="500px">
      <el-form :model="editRepairForm" label-width="80px">
        <el-form-item label="标题">
          <el-input v-model="editRepairForm.title" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="editRepairForm.description" type="textarea" />
        </el-form-item>
        <el-form-item label="地点">
          <el-input v-model="editRepairForm.location" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="editRepairForm.status">
            <el-option label="待处理" value="PENDING" />
            <el-option label="处理中" value="IN_PROGRESS" />
            <el-option label="已完成" value="COMPLETED" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理人">
          <el-select v-model="editRepairForm.handlerUserId" placeholder="请选择后勤人员">
            <el-option
              v-for="staff in logisticsStaffList"
              :key="staff.id"
              :label="staff.name"
              :value="staff.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="repairDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveRepair">保存</el-button>
      </template>
    </el-dialog>
    
    <!-- 新增/编辑后勤人员对话框 -->
    <el-dialog v-model="staffDialogVisible" :title="staffDialogTitle" width="500px">
      <el-form :model="editStaffForm"  ref="staffForm" label-width="80px" >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editStaffForm.username" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editStaffForm.name" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="editStaffForm.password" type="password" />
        </el-form-item>
        <el-form-item label="工作岗位" prop="position">
          <el-input v-model="editStaffForm.position" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="staffDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveStaff" >保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { 
  getAllRepairs, updateRepair, deleteRepair,
  getAllLogisticsStaff, addLogisticsStaff, updateLogisticsStaff, deleteLogisticsStaff
} from '../api'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()
const userStore = useUserStore()

const activeMenu = ref('repair')
const loading = ref(false)
const staffLoading = ref(false)

const repairs = ref([])
const staffList = ref([])
const logisticsStaffList = ref([])

// 报修管理分页
const repairCurrentPage = ref(1)
const repairPageSize = ref(5)
const repairTotal = ref(0)

// 后勤人员管理分页
const staffCurrentPage = ref(1)
const staffPageSize = ref(5)
const staffTotal = ref(0)

// 报修相关
const repairDialogVisible = ref(false)
const editRepairForm = reactive({
  id: null,
  title: '',
  description: '',
  location: '',
  status: '',
  handlerUserId: null
})

// 后勤人员相关
const staffDialogVisible = ref(false)
const staffDialogTitle = ref('新增后勤人员')
const editStaffForm = reactive({
  id: null,
  username: '',
  name: '',
  password: '',
  position: ''
})

onMounted(() => {
  loadRepairs()
  loadStaff()
  loadLogisticsStaff()
})

const handleMenuSelect = (index) => {
  activeMenu.value = index
}


const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    userStore.logout()
    ElMessage.success('已退出登录')
    router.push('/login')
  } catch (error) {
    // 用户取消退出
  }
}

// 报修管理
const loadRepairs = async () => {
  try {
    loading.value = true
    const response = await getAllRepairs()
    const allData = response.data || []
    repairTotal.value = allData.length
    
    // 客户端分页
    const startIndex = (repairCurrentPage.value - 1) * repairPageSize.value
    const endIndex = startIndex + repairPageSize.value
    repairs.value = allData.slice(startIndex, endIndex)
  } catch (error) {
    ElMessage.error('加载报修数据失败')
  } finally {
    loading.value = false
  }
}

const refreshRepairs = () => {
  repairCurrentPage.value = 1
  loadRepairs()
}

const editRepair = (row) => {
  Object.assign(editRepairForm, row)
  repairDialogVisible.value = true
}

const saveRepair = async () => {
  try {
    await ElMessageBox.confirm('确定要保存吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await updateRepair(editRepairForm)
    ElMessage.success('更新成功')
    repairDialogVisible.value = false
    loadRepairs()
  } catch (error) {
    ElMessage.error('更新失败')
  }
}

const deleteRepairItem = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这条报修记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await deleteRepair(id)
    ElMessage.success('删除成功')
    loadRepairs()
  } catch (error) { 
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 后勤人员管理
const loadStaff = async () => {
  try {
    staffLoading.value = true
    const response = await getAllLogisticsStaff()
    const allData = response.data || []
    staffTotal.value = allData.length
    
    // 客户端分页
    const startIndex = (staffCurrentPage.value - 1) * staffPageSize.value
    const endIndex = startIndex + staffPageSize.value
    staffList.value = allData.slice(startIndex, endIndex)
  } catch (error) {
    ElMessage.error('加载后勤人员数据失败')
  } finally {
    staffLoading.value = false
  }
}

const showAddStaffDialog = () => {
  staffDialogTitle.value = '新增后勤人员'
  Object.assign(editStaffForm, {
    id: null,
    username: '',
    name: '',
    password: '',
    position: ''
  })
  staffDialogVisible.value = true
}

const editStaff = (row) => {
  staffDialogTitle.value = '编辑后勤人员'
  Object.assign(editStaffForm, row)
  editStaffForm.password = ''
  staffDialogVisible.value = true
}

const saveStaff = async () => {
 
  try {
  await ElMessageBox.confirm('确定要保存吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
  })
    if (editStaffForm.id) {
      await updateLogisticsStaff(editStaffForm)
    ElMessage.success('保存成功')
    staffDialogVisible.value = false
    loadStaff()
    } else {
     // 前端非空校验
  if (!editStaffForm.username || !editStaffForm.name || !editStaffForm.password || !editStaffForm.position) {
    ElMessage.warning('请完整填写所有信息后再保存！')
   return
  }
    await addLogisticsStaff(editStaffForm)
    ElMessage.success('新增成功')
    staffDialogVisible.value = false
    loadStaff()
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const deleteStaff = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个后勤人员吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await deleteLogisticsStaff(id)
    ElMessage.success('删除成功')
    loadStaff()
  } catch (error) {
    if (error !== 'cancel') {
    
    }
  }
}

// 工具函数
const getStatusType = (status) => {
  const types = {
    'PENDING': 'warning',
    'IN_PROGRESS': 'primary',
    'COMPLETED': 'success',
    'CANCELLED': 'info'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    'PENDING': '待处理',
    'IN_PROGRESS': '处理中',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消'
  }
  return texts[status] || status
}

// 分页处理方法
const handleRepairSizeChange = (newSize) => {
  repairPageSize.value = newSize
  repairCurrentPage.value = 1
  loadRepairs()
}

const handleRepairCurrentChange = (newPage) => {
  repairCurrentPage.value = newPage
  loadRepairs()
}

const handleStaffSizeChange = (newSize) => {
  staffPageSize.value = newSize
  staffCurrentPage.value = 1
  loadStaff()
}

const handleStaffCurrentChange = (newPage) => {
  staffCurrentPage.value = newPage
  loadStaff()
}

const loadLogisticsStaff = async () => {
  try {
    const res = await getAllLogisticsStaff()
    logisticsStaffList.value = res.data || []
  } catch (e) {
    logisticsStaffList.value = []
  }
}
</script>

<style scoped>
.admin-container {
  height: 100vh;
}

.header {
  background: #409eff;
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.header-right .el-button {
  color: white;
  font-weight: 500;
}

.header-right .el-button:hover {
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
}

.sidebar {
  background: #f5f5f5;
}

.sidebar-menu {
  border-right: none;
}

.main-content {
  padding: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  margin: 0;
  color: #333;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style> 